package com.example.xxljobdemo.demos.job;

import com.alibaba.fastjson.JSON;
import com.example.xxljobdemo.demos.pojo.SeckillProductVo;
import com.example.xxljobdemo.demos.pojo.SeckillRedisKey;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SeckillProductJob {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @XxlJob("seckillProductCacheHandler")
    public void seckillProductCacheHandler(){
        SeckillProductVo seckillProductVo = new SeckillProductVo();
        seckillProductVo.setId(1);
        seckillProductVo.setName("面包");
        seckillProductVo.setDescription("好吃不贵");

        //10点秒杀，从数据库查询出秒杀商品存入redis
        List<SeckillProductVo> productVos_10 = new ArrayList<>();
        productVos_10.add(seckillProductVo);
        int time = 10;
        syncToRedis(time, productVos_10);

        //12点秒杀，从数据库查询出秒杀商品存入redis
        List<SeckillProductVo> productVos_12 = new ArrayList<>();
        productVos_12.add(seckillProductVo);
        time = 12;
        syncToRedis(time, productVos_12);
    }

    private void syncToRedis(int time, List<SeckillProductVo> vos) {

        String key = SeckillRedisKey.SECKILL_PRODUCT_HASH + time + "";
        //清除之前的
        redisTemplate.delete(key);
        for (SeckillProductVo vo : vos) {
            redisTemplate.opsForHash().put(key, vo.getId() + "", JSON.toJSONString(vo));
        }

    }

}



